package com.ygqh.baby.controller.mobile;

import com.foxinmy.weixin4j.util.StringUtil;
import com.ygqh.baby.ao.*;
import com.ygqh.baby.constant.RedisConstant;
import com.ygqh.baby.exception.YgException;
import com.ygqh.baby.handler.HolidayNoticeHandler;
import com.ygqh.baby.handler.LoginHandler;
import com.ygqh.baby.model.YgLoginModel;
import com.ygqh.baby.model.YgUserModel;
import com.ygqh.baby.po.YgUser;
import com.ygqh.baby.po.YgUserBalance;
import com.ygqh.baby.redis.RedisDao;
import com.ygqh.baby.service.*;
import com.ygqh.baby.service.impl.DocumentConstant;
import com.ygqh.baby.service.task.YgAsynClient;
import com.ygqh.baby.utils.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/app/admin")
public class AdminController extends BaseController {

    private Logger logger = Logger.getLogger(AdminController.class);

    @Autowired
    private YgUserService ygUserService;
    @Autowired
    private YgAsynClient ygAsynClient;
    @Autowired
    private SmsService smsService;
    @Autowired
    private DocumentConstant documentConstant;
    @Autowired
    private RedisDao redisDao;
    @Autowired
    private YgCardCouponDetailService ygCardCouponDetailService;
    @Autowired
    private YgAgentInviteRecordService ygAgentInviteRecordService;
    @Autowired
    private YgUserBalanceService ygUserBalanceService;
    @Autowired
    private LoginHandler loginHandler;

    @Value("${validate.send.count}")
    private Long validateSendCount;
    @Value("${validate.send.interval}")
    private Long validateSendInterval;
    @Value("${validate.valid.time}")
    private Long validateValidTime;
    @Autowired
    private YgUserBalanceService userBalanceService;
    @Value("${default.head.url}")
    private String defaultHeadUrl;
    @Value("${default.nickName.prefix}")
    private String defaultNickNamePrefix;
    @Value("${sms.isSend}")
    private Boolean isSend;

    @RequestMapping(value = "/unauthorized")
    @ResponseBody
    public ResponseEntity unauthorized(String callback) {
        return ResponseEntity.success(new YgLoginModel("REDIRECT_LONGIN_PAGE", documentConstant.REDIRECT_LONGIN_PAGE));
    }

    @RequestMapping(value = "autoLogin")
    @ResponseBody
    public ResponseEntity autoLogin(@RequestParam(required = true) String userName, @RequestParam(required = true) AppType appType) throws Exception {
        YgUser user = ygUserService.findBySourceCode(userName);
        if (user != null) {
            YgLoginModel loginSilent = loginHandler.loginSilent(user, appType);
            return ResponseEntity.success(loginSilent);
        } else {
            return ResponseEntity.error(CodeConstant.PhoneNotExist);
        }

    }

    /**
     * 是否登录
     *
     * @return
     */
    @RequestMapping(value = "/isLogin")
    @ResponseBody
    public ResponseEntity isLogin() {
        YgLoginModel model = new YgLoginModel("LOGIN_SUCCESS", documentConstant.LOGIN_SUCCESS);
        Map<String, Object> data = new HashMap<>();
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            YgUser user = (YgUser) subject.getPrincipal();
            data.put("userId", user.getId());
            data.put("sessionId", subject.getSession().getId());
            model.setIsBand(StringUtils.isNotBlank(user.getTelPhone()));
        }
        model.setUser(data);
        return ResponseEntity.success(model);
    }

    /**
     * 判断是否是新客
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/isNewCustom")
    @ResponseBody
    public ResponseEntity isNewCustom(HttpServletRequest request) throws Exception {
        YgLoginModel model = new YgLoginModel("LOGIN_SUCCESS", documentConstant.LOGIN_SUCCESS);
        YgUser user = SessionUtil.getCurrentUser();
        model.setUser(ygUserService.isNewCustom(user.getId()));
        return ResponseEntity.success(model);
    }

    /**
     * 登录
     *
     * @param username
     * @param password
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/login")
    @ResponseBody
    public ResponseEntity login(@RequestParam(required = true) String username, String password, HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        password = "123456a";

        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        YgLoginModel model = new YgLoginModel("LOGIN_SUCCESS", documentConstant.LOGIN_SUCCESS);
        try {
            subject.login(token);
        } catch (UnknownAccountException e) {
            model = new YgLoginModel("UNKNOWN_ACCOUNT", documentConstant.UNKNOWN_ACCOUNT);
        } catch (IncorrectCredentialsException e) {
            model = new YgLoginModel("INCORRECTCREDENTIALS", documentConstant.INCORRECTCREDENTIALS);
        } catch (Exception e) {
            e.printStackTrace();
            model = new YgLoginModel("UNKNOWN_ERROR", documentConstant.UNKNOWN_ERROR);
        }
        ;
        logger.debug("session id===============" + request.getSession().getId());
        if (model.getKey().equals("LOGIN_SUCCESS")) {
            model.setUser(subject.getPrincipal());
            model.setSessionId(subject.getSession().getId());
            return ResponseEntity.success(model);
        } else {
            return ResponseEntity.error(model);
        }
    }

    /**
     * 发送验证码-----------------------正常
     *
     * @param
     * @param username
     * @return
     * @throws Exception
     */
    @RequestMapping("/sendValidateCode")
    @ResponseBody
    public ResponseEntity sendValidateCode(@RequestParam(required = true) String username) throws Exception {
        String validateCodeString;
        if (isSend) {
            validateCodeString = CommonUtil.generatorSmsValidateCode() + "";
        } else {
            validateCodeString = "123456";
        }
        ValidateCode originalValidateCode = ygUserService.selectValidateCodeToRedis(username);
        ValidateCode validateCode = new ValidateCode(validateCodeString, 0L);
        logger.debug("sendValidateCode===========" + validateCode);
        if (originalValidateCode != null) {
            // 判断发送信息次数是否超过限定值
            if (originalValidateCode.getSendCount() > validateSendCount) {
                return new ResponseEntity(CodeConstant.VCodeSendCountOver.getCode(), CodeConstant.VCodeSendCountOver.getTitle(), null);
            }

            if (originalValidateCode.getSendCount() > 1) {
                // 判断是否发送过于频繁
                Long currentTime = System.currentTimeMillis();
                System.out.println((currentTime - originalValidateCode.getSendTime()) / 1000 + "----------------------------------");
                if ((currentTime - originalValidateCode.getSendTime()) / 1000 < validateSendInterval) {
                    return new ResponseEntity(CodeConstant.VCodeSendHighFrequency.getCode(), CodeConstant.VCodeSendHighFrequency.getTitle(), null);
                }
            }

            Long count = originalValidateCode.getSendCount() + 1L;
            validateCode.setSendCount(count);
            validateCode.setSendTime(System.currentTimeMillis());
        } else {
            validateCode.setSendTime(System.currentTimeMillis());
        }
        String smsContent = PropertiesUtil.getData("/prop/sms.properties", "sms.content", validateCodeString);
        smsService.sendSms(username, smsContent, true);
        int expire = (validateValidTime.intValue() * 60 * 1000);
        ygUserService.saveValidateCodeToRedis(username, validateCode, expire);
        return new ResponseEntity(CodeConstant.Success.getCode(), CodeConstant.Success.getTitle(), null);
    }

    /**
     * 注册
     *
     * @param
     * @param username
     * @param password
     * @param validateCode
     * @return
     */
    @RequestMapping("/register")
    @ResponseBody
    public ResponseEntity register(@RequestParam(required = true) String username, String password, @RequestParam(required = true) String validateCode,
                                   String fromCode, String groupTag, @RequestParam(required = true) AppType appType) {
        password = password == null ? "123456a" : password;
        ValidateCode rightValidateCode = ygUserService.selectValidateCodeToRedis(username);
        YgUser ygUser;
        // 判断是否匹配
        if (rightValidateCode == null || !rightValidateCode.getCode().equals(validateCode)) {
            return new ResponseEntity(CodeConstant.VCodeError.getCode(), CodeConstant.VCodeError.getTitle(), null);
        }

        Long currentTime = System.currentTimeMillis();
        Long minute = (currentTime - rightValidateCode.getSendTime()) / 1000 / 60;
        logger.debug("reigster===" + minute);

        // 判断是否失效
        if (minute > validateValidTime) {
            return new ResponseEntity(CodeConstant.VCodeError.getCode(), CodeConstant.VCodeError.getTitle(), null);
        }

        if (ygUserService.findByUserName(username) != null) {
            return new ResponseEntity(CodeConstant.PhoneExist.getCode(), CodeConstant.PhoneExist.getTitle(), null);
        }
        ygUser = new YgUser();
        ygUser.setUserName(username);
        ygUser.setPassword(password);
        ygUser.setTelPhone(username);
        ygUser.setFromCode(fromCode);
        ygUser.setSourceCode(username);
        ygUser.setBabyBirthday(null);
        ygUser.setBabyGender(null);
        ygUser.setGender(null);
        ygUser.setHeadImageUrl(defaultHeadUrl);
        ygUser.setGroupTag(groupTag);
        if (username.length() >= 7) {
            ygUser.setNickName(defaultNickNamePrefix + username.substring(7, 11));
        }
        ygUser.setCreateTime(new Date());

        ygUserService.save(ygUser);

        YgUserBalance userBalance = new YgUserBalance();
        userBalance.setBalancePrice(new BigDecimal(0));
        userBalance.setCreateTime(new Date());
        userBalance.setFreezePrice(new BigDecimal(0));
        userBalance.setPreincomePrice(new BigDecimal(0));
        userBalance.setUserId(ygUser.getId());
        userBalance.setWithdrawPrice(new BigDecimal(0));
        userBalanceService.save(userBalance);

        doPullNEWBussness(fromCode, ygUser.getUserName(), ygUser.getNickName(), null);

        // 注册新用户赠送拉新卡券
        ygCardCouponDetailService.asyncGivePullNewCard(ygUser.getId());

        YgLoginModel loginSilent = loginHandler.loginSilent(ygUser, appType);
        return new ResponseEntity(CodeConstant.Success.getCode(), CodeConstant.Success.getTitle(), loginSilent);

    }

    @RequestMapping("/updateFromCode")
    @ResponseBody
    public ResponseEntity updateFromCode(@RequestParam(required = true) String username, @RequestParam(required = true) String fromCode,
                                         @RequestParam(required = true) String callback) {
        YgUser user = ygUserService.findByUserName(username);
        if (user == null) {
            return ResponseEntity.error("USER_NULL");
        }
        user.setFromCode(fromCode);
        ygUserService.update(user);
        return ResponseEntity.success();
    }

    /**
     * 用户是否存在
     *
     * @param username
     * @return
     */
    @RequestMapping("/userIsExist")
    @ResponseBody
    public ResponseEntity userIsExist(@RequestParam(required = true) String username) {
        YgUser user = ygUserService.findByUserName(username);
        Map<String, Boolean> map = new HashMap<String, Boolean>();
        if (user == null) {
            map.put("isExist", false);
        } else {
            map.put("isExist", true);
        }
        return new ResponseEntity(CodeConstant.Success.getCode(), CodeConstant.Success.getTitle(), map);
    }

    @RequestMapping(value = "logout")
    @ResponseBody
    public ResponseEntity logout(@RequestParam(required = true) AppType appType, HttpServletRequest request) throws Exception {
        try {
            YgUser user = SessionUtil.getCurrentUser();
            loginHandler.resetAppToken(user.getId().toString(), appType, null);
            Subject subject = SecurityUtils.getSubject();
            subject.logout();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResponseEntity(com.ygqh.baby.ao.CodeConstant.Success);
    }

    @RequestMapping(value = "hasBind")
    @ResponseBody
    public ResponseEntity hasBindPhone(@RequestParam(required = true) String unionid, @RequestParam(required = true) AppType appType) throws Exception {
        YgUser user = ygUserService.findByUuid(unionid);
        Boolean hasBind = false;
        Map<String, Object> map = new HashMap<>();
        YgLoginModel model = null;
        if (user != null && StringUtil.isNotBlank(user.getUserName())) {
            hasBind = true;
            model = loginHandler.loginSilent(user, appType);
        }
        map.put("hasBind", hasBind);
        map.put("userInfo", model);
        return new ResponseEntity(CodeConstant.Success.getCode(), CodeConstant.Success.getTitle(), map);
    }

    public final static AppType[] APP_ARR = {AppType.Android, AppType.Ios};

    /**
     * 绑定手机号
     *
     * @param unionid
     * @param username
     * @param nickName
     * @param headUrl
     * @param validateCode
     * @param appType
     * @param fromCode
     * @param groupTag
     * @return
     */
    @RequestMapping(value = "bind")
    @ResponseBody
    public ResponseEntity bind(@RequestParam String unionid, @RequestParam String username, String nickName, String headUrl,
                               @RequestParam String validateCode, @RequestParam AppType appType, String fromCode, String groupTag) {
        try {
            ValidateCode rightValidateCode = ygUserService.selectValidateCodeToRedis(username);

            // 判断是否匹配
            if (rightValidateCode == null || !rightValidateCode.getCode().equals(validateCode)) {
                return new ResponseEntity(CodeConstant.VCodeError.getCode(), CodeConstant.VCodeError.getTitle(), null);
            }

            YgUser ygUser = ygUserService.findByUserName(username);

            if (ygUser != null && ygUser.getUuid() != null) {
                return new ResponseEntity(CodeConstant.PhoneExist.getCode(), CodeConstant.PhoneExist.getTitle(), null);
            } else if (ygUser != null) {
                YgUser userInfo = new YgUser();
                userInfo.setId(ygUser.getId());
                userInfo.setUuid(unionid);
                userInfo.setNickName(nickName);
                userInfo.setHeadImageUrl(headUrl);
                if (userInfo.getFromCode() == null) {
                    if (fromCode != null) {
                        ygUser.setFromCode(fromCode);
                    }
                }
                ygUserService.updateUserInfo(ygUser);
            } else {
                ygUser = ygUserService.findByUuid(unionid);
                if (ygUser != null) {
                    ygUser.setUserName(username);
                    ygUser.setTelPhone(username);
                    ygUser.setPassword("123456a");
                    ygUser.setSourceCode(username);
                    ygUser.setUpdateTime(new Date());
                    ygUserService.update(ygUser);
                } else {
                    ygUser = new YgUser();
                    ygUser.setUserName(username);
                    ygUser.setPassword("123456a");
                    ygUser.setTelPhone(username);
                    ygUser.setFromCode(fromCode);
                    ygUser.setSourceCode(username);
                    ygUser.setBabyBirthday(null);
                    ygUser.setBabyGender(null);
                    ygUser.setGender(null);
                    if (StringUtil.isBlank(headUrl)) {
                        ygUser.setHeadImageUrl(defaultHeadUrl);
                    }
                    ygUser.setHeadImageUrl(headUrl);
                    ygUser.setGroupTag(groupTag);
                    if (StringUtil.isBlank(nickName)) {
                        ygUser.setNickName(defaultNickNamePrefix + username.substring(7, 11));
                    }
                    ygUser.setNickName(nickName);
                    ygUser.setCreateTime(new Date());
                    ygUser.setAppType(appType);
                    ygUser.setUuid(unionid);

                    ygUserService.save(ygUser);

                    YgUserBalance userBalance = new YgUserBalance();
                    userBalance.setBalancePrice(new BigDecimal(0));
                    userBalance.setCreateTime(new Date());
                    userBalance.setFreezePrice(new BigDecimal(0));
                    userBalance.setPreincomePrice(new BigDecimal(0));
                    userBalance.setUserId(ygUser.getId());
                    userBalance.setWithdrawPrice(new BigDecimal(0));
                    userBalanceService.save(userBalance);

                    doPullNEWBussness(fromCode, ygUser.getUserName(), ygUser.getNickName(), null);
                    ygUser.setIsNewCustomer(true);

                }
            }

            YgLoginModel model = loginHandler.loginSilent(ygUser, appType);
            model.setIsBand(Boolean.TRUE);
            return new ResponseEntity(CodeConstant.Success.getCode(), CodeConstant.Success.getTitle(), model);
        } catch (Exception e) {
            logger.error(e.getMessage() + ";绑定手机号失败：username=" + username + ";unionid=" + unionid + ";AppType=" + appType);
            e.printStackTrace();
            return new ResponseEntity(CodeConstant.Error.getCode(), CodeConstant.Error.getTitle(), e.getMessage());
        }
    }

    /**
     * 处理拉新
     *
     * @param fromCode
     * @param userName
     * @param nickName
     */
    private void doPullNEWBussness(String fromCode, String userName, String nickName, String openId) {
        try {
            YgUser fromUser = ygUserService.findBySourceCode(fromCode);
            if (fromUser != null && fromUser.getUserType().equals(UserType.UserAgent)) {
                // 发送微信消息
                ygAsynClient.sendInviteRegisterSuccessMsg(fromUser.getOpenId(), fromCode, userName, nickName);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "isGuide")
    @ResponseBody
    public ResponseEntity isGuide(@RequestParam(required = true) String callback) throws Exception {
        Boolean flag = ygUserService.isGuide(SessionUtil.getCurrentUser().getId());
        return ResponseEntity.success(flag);
    }

    @RequestMapping(value = "findUserById")
    @ResponseBody
    public ResponseEntity findUserById(@RequestParam(required = true) Long userId) throws Exception {
        YgUserModel userInfo = ygUserService.findUserInfo(userId);
        if (userInfo == null) {
            return ResponseEntity.error("用户不存在");
        }
        String birthday = DateConvertUtils.getBabyBirthday(userInfo.getBabyBirthday());
        userInfo.setbBirthday(birthday);
        return ResponseEntity.success(userInfo);
    }

    /**
     * 验证码登录
     *
     * @param username
     * @return
     */
    @RequestMapping(value = "/validateCodeLogin")
    @ResponseBody
    public ResponseEntity validateCodeLogin(@RequestParam String username, @RequestParam String validateCode,
                                            @RequestParam AppType appType) {

        YgUser user = ygUserService.findByUserName(username);
        YgLoginModel model;

        if (user == null) {
            return new ResponseEntity(CodeConstant.PhoneNotExist.getCode(), CodeConstant.PhoneNotExist.getTitle(), null);
        }

        ValidateCode rightValidateCode = ygUserService.selectValidateCodeToRedis(username);

        // 判断是否匹配
        if (rightValidateCode == null || !rightValidateCode.getCode().equals(validateCode)) {
            return new ResponseEntity(CodeConstant.VCodeError.getCode(), CodeConstant.VCodeError.getTitle(), null);
        }

        Long currentTime = System.currentTimeMillis();
        Long minute = (currentTime - rightValidateCode.getSendTime()) / 1000 / 60;

        // 判断是否失效
        if (minute > validateValidTime) {
            return new ResponseEntity(CodeConstant.VCodeError.getCode(), CodeConstant.VCodeError.getTitle(), null);
        }

        model = loginHandler.loginSilent(user, appType);

        return new ResponseEntity(CodeConstant.Success.getCode(), CodeConstant.Success.getTitle(), model);

    }

    @RequestMapping(value = "getImgCode")
    public void getImgCode(HttpServletRequest request, HttpServletResponse response) throws YgException, IOException {
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        // 生成随机字串
        String attribute = (String) request.getSession().getAttribute(RedisConstant.MOBILE_IMG_VALIDATE_CODE);
        System.out.println(attribute);
        String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
        request.getSession().setAttribute(RedisConstant.MOBILE_IMG_VALIDATE_CODE, verifyCode.toLowerCase());
        // 生成图片
        VerifyCodeUtils.outputImage(100, 50, response.getOutputStream(), verifyCode);
    }

    @RequestMapping("/sendValidateCodeNew")
    @ResponseBody
    public ResponseEntity sendValidateCodeNew(@RequestParam(required = true) String username, String imgCode, HttpServletRequest request) throws Exception {
        String validateCodeString;
        if (isSend && !"13301296315".equals(username)) {
            validateCodeString = CommonUtil.generatorSmsValidateCode() + "";
        } else {
            validateCodeString = "123456";
        }
        ValidateCode originalValidateCode = ygUserService.selectValidateCodeToRedis(username);
        ValidateCode validateCode = new ValidateCode(validateCodeString, 1L);
        logger.debug("sendValidateCode===========" + validateCode);
        if (originalValidateCode != null) {
            // 判断发送信息次数是否超过限定值,需要输入图片验证码
            if (originalValidateCode.getSendCount() > validateSendCount) {
                String imgVerifyCode = (String) request.getSession().getAttribute(RedisConstant.MOBILE_IMG_VALIDATE_CODE);
                if (!imgVerifyCode.equals(imgCode)) {
                    return ResponseEntity.error("图片验证码输入错误");
                }
            }

            Long count = originalValidateCode.getSendCount() + 1L;
            validateCode.setSendCount(count);
        }
        String smsContent = PropertiesUtil.getData("/prop/sms.properties", "sms.content", validateCodeString);
        smsService.sendSms(username, smsContent, true);
        int expire = (validateValidTime.intValue() * 60 * 1000);
        ygUserService.saveValidateCodeToRedis(username, validateCode, expire);
        return ResponseEntity.success(validateCode.getSendCount());
    }

    @RequestMapping(value = "loginByUnionId")
    @ResponseBody
    public ResponseEntity loginByUnionId(@RequestParam String unionId, AppType appType, String fromCode, String linkCode) {
        YgUser user = ygUserService.findByUuid(unionId);
        if (user != null) {
            ygUserBalanceService.processUserBalance(user.getId());
            ygAgentInviteRecordService.processFromCodeByUserAgent(user, fromCode);

            YgLoginModel loginSilent = loginHandler.loginSilent(user, appType);
            user.setSourceCode(ShareCodeUtil.toSerialCode(user.getId()));
            if (StringUtils.isNotBlank(user.getTelPhone())) {
                loginSilent.setIsBand(Boolean.TRUE);
            }
            return ResponseEntity.success(loginSilent);
        } else {
            return ResponseEntity.error("用户不存在");
        }

    }

    /**
     * 获取邀请人信息
     *
     * @param sourceCode 邀请人source
     * @return
     */
    @RequestMapping("getShareUser")
    @ResponseBody
    public ResponseEntity getShareUser(String sourceCode) {
        String headImageUrl = "https://yiigoo-tmp.oss-cn-shanghai.aliyuncs.com/default/default_yijiadian_head.jpg";
        String nickName = "壹家店";
        try {
            if (org.apache.commons.lang.StringUtils.isNotBlank(sourceCode)) {
                long id = ShareCodeUtil.codeToId(sourceCode);
                YgUser user = ygUserService.findById(id);
                if (user != null) {
                    headImageUrl = user.getHeadImageUrl();
                    nickName = user.getNickName();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        Map<String, Object> data = new HashMap<>();
        data.put("headImageUrl", headImageUrl);
        data.put("nickName", nickName);
        return ResponseEntity.success(data);
    }

    /**
     * 绑定手机号（已登录用户绑定手机号）
     *
     * @param username
     * @param validateCode
     * @param appType
     * @return
     */
    @RequestMapping(value = "bindV2")
    @ResponseBody
    public ResponseEntity bindV2(@RequestParam String username, @RequestParam String validateCode,
                                 @RequestParam AppType appType) {
        ValidateCode rightValidateCode = ygUserService.selectValidateCodeToRedis(username);
        // 判断手机验证码是否匹配
        if (rightValidateCode == null || !rightValidateCode.getCode().equals(validateCode)) {
            return new ResponseEntity(CodeConstant.VCodeError.getCode(), CodeConstant.VCodeError.getTitle(), null);
        }
        YgUser currentUser = SessionUtil.getCurrentUser();
        String unionid = currentUser.getUuid();

        // 查询手机号用户
        YgUser ygUser = ygUserService.findByUserName(username);
        if (ygUser != null) {
            if (StringUtils.isNotBlank(ygUser.getUuid()) && unionid.equals(ygUser.getUuid())) {
                return ResponseEntity.error("手机号已绑定成功，不可重复操作", null);
            }
            return ResponseEntity.error(CodeConstant.PhoneExist.getTitle(), null);
        }

        // 查询uuid用户
        ygUser = ygUserService.findByUuid(unionid);
        if (ygUser == null) {
            return ResponseEntity.error("用户数据异常，请重新授权登录", null);
        }

        String oldSourceCode = ygUser.getSourceCode();
        // 绑定成功
        ygUser.setUserName(username);
        ygUser.setTelPhone(username);
        ygUser.setPassword("123456a");
        ygUser.setSourceCode(username);
        ygUser.setUpdateTime(new Date());
        ygUserService.update(ygUser);
        ygUserService.updateFromCode(oldSourceCode, username);

        YgLoginModel model = loginHandler.loginSilent(ygUser, appType);
        model.setIsBand(Boolean.TRUE);
        return new ResponseEntity(CodeConstant.Success.getCode(), CodeConstant.Success.getTitle(), model);
    }

    @Autowired
    private HolidayNoticeHandler holidayNoticeHandler;

    @RequestMapping("getHolidayNotice")
    @ResponseBody
    public ResponseEntity getHolidayNotice(@RequestParam(defaultValue = "true") Boolean checkDate) {
        Map holidayNotice = holidayNoticeHandler.getHolidayNotice(checkDate);
        return ResponseEntity.success(holidayNotice);
    }
}
